package com.zx.ishopping.services.impl;

import com.zx.ishopping.Constants.InsertConstant;
import com.zx.ishopping.entity.Cart;
import com.zx.ishopping.entity.CartItem;
import com.zx.ishopping.entity.Products;
import com.zx.ishopping.exceptions.CartItemException;
import com.zx.ishopping.mapper.CartItemMapper;
import com.zx.ishopping.mapper.CartMapper;
import com.zx.ishopping.mapper.ProductMapper;
import com.zx.ishopping.services.CartItemsService;
import com.zx.ishopping.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class CartItemsServiceImpl implements CartItemsService {

    @Autowired
    private ProductMapper productMapper;
    
    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private CartItemMapper cartItemMapper;
    

    /**
     * 添加商品至购物车
     * @param productId
     */
    @Transactional
    @Override
    public void addCartItems(Long productId) {
        
        
        
        
        CartItem cartItem = new CartItem();
        //获取购物车id
        Long userId = ThreadLocalUtil.get();
        Cart cartInfo = cartMapper.getCartInfo(userId);
        
        //根据购物车id和商品id查询购物车中是否存在这个商品
        int row = cartItemMapper.getCartItemByCartIdAndProductId(cartInfo.getId(),productId);
        
        if (row > 0){
            throw new CartItemException(InsertConstant.EXIST_CART_ITEMS);
        }
        
        //添加购物车项的 购物车id
        cartItem.setCartId(cartInfo.getId());

        cartItem.setProductId(productId);
        cartItem.setQuantity(1);
        Products products = productMapper.getById(productId);
        cartItem.setTotalPrice(products.getPrice());//一次只能添加一件商品
        cartItemMapper.addCartItem(cartItem);
        
        //添加成功后，修改购物车总金额和商品数量
        cartInfo.setTotalPrice(cartInfo.getTotalPrice().add(products.getPrice()));
        cartInfo.setQuantity(cartInfo.getQuantity()+1);
        cartMapper.update(cartInfo);
        
        
    }
}
